<template>
  <div>
    <a-form-model ref="form" :model="model" :rules="validatorRules">
      <a-form-model-item required prop="username">
        <a-input v-model="model.username" size="large" placeholder="请输入帐户名 / admin">
          <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input>
      </a-form-model-item>
      <a-form-model-item required prop="password">
        <a-input v-model="model.password" size="large" type="password" autocomplete="false" placeholder="请输入密码 / 123456">
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
        </a-input>
      </a-form-model-item>

      <a-row :gutter="0">
        <a-col :span="16">
          <a-form-model-item required prop="inputCode">
            <a-input v-model="model.inputCode" size="large" type="text" placeholder="请输入验证码">
              <a-icon slot="prefix" type="smile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-model-item>
        </a-col>

      </a-row>


    </a-form-model>
    <div class="slider">
      <div class="content">
        <div class="bg-img-div" ref="bgImg">
          <img id="bg-img" :src="backgroundImage" alt/>
        </div>
        <div class="slider-img-div" ref="sliderImg">
          <img id="slider-img" :src="sliderImage" alt/>
        </div>
      </div>
      <div class="slider-move">
        <div class="slider-move-track">
          拖动滑块完成拼图
        </div>
        <div class="slider-move-btn" ref="sliderBtn"
        />
      </div>
    </div>

    <!--  <div class="slider-move">
        <div class="slider-move-track">
          拖动滑块完成拼图
        </div>
        <div class="slider-move-btn" id="slider-move-btn" style="background-position: -5px 11.7963%; transform: translate(0px, 0px);"></div>
      </div>
-->

    <div class="bottom">
      <div class="close-btn" id="slider-close-btn"></div>
      <div class="refresh-btn" id="slider-refresh-btn"></div>
    </div>
  </div>



</template>

<script>
  import { getAction } from '@/api/manage'
  import { postAction } from '@/api/manage'
  import Vue from 'vue'
  import { mapActions } from 'vuex'
  import moment from "moment";

  export default {
    name: 'LoginAccount',

    data(){
      return {
        requestCodeSuccess: false,
        randCodeImage: '',
        currdatetime: '',
        loginType: 0,
        currentCaptchaId: '',
        backgroundImage: '',
        sliderImage: '',
        isMouseDown: false,
        originX: 0,
        originY: 0,
        startSlidingTime: null,
        entSlidingTime: null,
        trackList: [],
        bgImageWidth: 0,
        bgImageHeight: 0,
        sliderImageWidth: 0,
        sliderImageHeight: 0,
        model:{
          username: '',
          password: '',
          inputCode: ''
        },
        validatorRules:{
          username: [
            { required: true, message: '请输入用户名!' },
            { validator: this.handleUsernameOrEmail }
          ],
          password: [{
            required: true, message: '请输入密码!', validator: 'click'
          }],
          inputCode: [{
            required: false, message: '请输入验证码!'
          }]
        }

      }
    },

    created() {
      this.refreshCaptcha();
      // this.handleChangeNewCheckCode();
    },

    mounted() {

      // this.refreshCaptcha();
      window.addEventListener('touchstart', this.handleDragStart);
      window.addEventListener('touchmove', this.handleDragMove);
      window.addEventListener('touchend', this.handleDragEnd);

      window.addEventListener('mousedown', this.handleDragStart);
      window.addEventListener('mousemove', this.handleDragMove);
      window.addEventListener('mouseup', this.handleDragEnd);
    },


    methods:{
      ...mapActions(['Login']),


      /**刷新验证码*/
      /*handleChangeCheckCode(){
        this.currdatetime = new Date().getTime();
        this.model.inputCode = ''
        getAction(`/sys/randomImage/${this.currdatetime}`).then(res=>{
          if(res.success){
            this.randCodeImage = res.result
            this.requestCodeSuccess=true
          }else{
            this.$message.error(res.message)
            this.requestCodeSuccess=false
          }
        }).catch(()=>{
          this.requestCodeSuccess=false
        })
      },*/

      refreshCaptcha() {
        this.currentCaptchaId= ''
        this.backgroundImage= ''
        this.sliderImage= ''
        this.isMouseDown= false
        this.originX= 0
        this.originY= 0
        this.startSlidingTime= null
        this.entSlidingTime= null
        this.trackList= []
        this.bgImageWidth= 0
        this.bgImageHeight= 0
        this.sliderImageWidth= 0
        this.sliderImageHeight= 0
        this.currdatetime = new Date().getTime();
        this.model.inputCode = ''

        getAction(`/sys/randomNewImage/${this.currdatetime}`).then(res=>{
          if(res.success){
            let data = res.result;
            this.backgroundImage = data.backgroundImage;
            this.sliderImage = data.sliderImage;
            this.currentCaptchaId = data.randomX+data.bgImageHeight;
            this.$refs.sliderImg.style.transform = 'translate(0px, 0px)';
            this.$refs.sliderBtn.style.transform = 'translate(0px, 0px)';

            this.requestCodeSuccess=true
          }else{
            this.$message.error(res.message)
            this.requestCodeSuccess=false
          }
        }).catch(()=>{
          this.requestCodeSuccess=false
        })

      },
      valid() {

        let data = {
          bgImageWidth: this.$refs.bgImg.clientWidth,
          bgImageHeight: this.$refs.bgImg.clientHeight,
          sliderImageWidth: this.$refs.sliderImg.clientWidth,
          sliderImageHeight: this.$refs.sliderImg.clientHeight,
          startSlidingTime: moment(this.startSlidingTime).format('YYYY-MM-DD HH:mm:ss'),
          entSlidingTime: moment(this.entSlidingTime).format('YYYY-MM-DD HH:mm:ss') ,
          trackList: this.trackList,
        };

        postAction("/sys/check?key=" + this.currentCaptchaId,data).then((res)=>{
          debugger;
          if(res.success){
            debugger;
            console.log("========",res.result);
            if(res.result){

            }else{
              // this.$emit('fail', "校验失败");
              //this.refreshCaptcha();
            }
            //that.$message.success(res.message);
            //this.$emit('success',res.result);
            // that.loadData();
            //that.onClearSelected();
          }else{
            this.refreshCaptcha();
          }
        });

      },
      handleDragStart(e) {
        this.startSlidingTime = new Date();
        // 获取拖拽起始位置坐标
        this.originX = e.clientX || e.touches[0].clientX;
        this.originY = e.clientY || e.touches[0].clientY;
        this.isMouseDown = true;
      },
      handleDragMove(ev){
        if (!this.isMouseDown) return false;
        const w = 206;//滑道宽度
        // 获取拖拽移动的距离
        const eventX = ev.clientX || ev.touches[0].clientX;
        const eventY = ev.clientY || ev.touches[0].clientY;
        let moveX = eventX - this.originX;
        let moveY = eventY - this.originY;
        this.trackList.push({x: moveX, y: moveY, t: (new Date().getTime() -this. startSlidingTime.getTime())});
        if (moveX < 0)
          moveX = 0;
        else if (moveX > w)
          moveX = w;
        this.$refs.sliderImg.style.transform = 'translate(' + moveX + 'px, 0px)';
        this.$refs.sliderBtn.style.transform = 'translate(' + moveX + 'px, 0px)';
      },
      handleDragEnd(ev){
        if (!this.isMouseDown) return false;
        this.isMouseDown = false;
        const eventX = ev.clientX || ev.changedTouches[0].clientX;
        if (eventX === this.originX) return false;
        this.entSlidingTime = new Date();
        this.$refs.sliderImg.style.transform = 'translate(0px, 0px)';
        this.$refs.sliderBtn.style.transform = 'translate(0px, 0px)';
        this.valid();
      },

      // 判断登录类型
      handleUsernameOrEmail (rule, value, callback) {
        const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
        if (regex.test(value)) {
          this.loginType = 0
        } else {
          this.loginType = 1
        }
        callback()
      },
      /**
       * 验证字段
       * @param arr
       * @param callback
       */
      validateFields(arr, callback){
        let promiseArray = []
        for(let item of arr){
          let p = new Promise((resolve, reject) => {
            this.$refs['form'].validateField(item, (err)=>{
              if(!err){
                resolve();
              }else{
                reject(err);
              }
            })
          });
          promiseArray.push(p)
        }
        Promise.all(promiseArray).then(()=>{
          callback()
        }).catch(err=>{
          callback(err)
        })
      },
      acceptUsername(username){
        this.model['username'] = username
      },
      //账号密码登录
      handleLogin(rememberMe){
        debugger;
        this.validateFields([ 'username', 'password', 'inputCode' ], (err)=>{
          if(!err){
            let loginParams = {
              username: this.model.username,
              password: this.model.password,
              captcha: this.model.inputCode,
              checkKey: this.currdatetime,
              remember_me: rememberMe,
            }
            console.log("登录参数", loginParams)
            this.Login(loginParams).then((res) => {
              this.$emit('success', res.result)
            }).catch((err) => {
              this.$emit('fail', err)
            });
          }else{
            this.$emit('validateFail')
          }
        })
      }


    }

  }
</script>


<style scoped>
  .slider {
    background-color: #fff;
    width: 278px;
    height: 285px;
    z-index: 999;
    box-sizing: border-box;
    padding: 9px;
    border-radius: 6px;
    box-shadow: 0 0 11px 0 #999999;
  }

  .slider .content {
    width: 100%;
    height: 159px;
    position: relative;
  }

  .bg-img-div {
    width: 100%;
    height: 100%;
    position: absolute;
    transform: translate(0px, 0px);
  }

  .slider-img-div {
    height: 100%;
    position: absolute;
    transform: translate(0px, 0px);
  }

  .bg-img-div img {
    width: 100%;
  }

  .slider-img-div img {
    height: 100%;
  }

  .slider .slider-move {
    height: 60px;
    width: 100%;
    margin: 11px 0;
    position: relative;
  }

  .slider .bottom {
    height: 19px;
    width: 100%;
  }

  .refresh-btn, .close-btn, .slider-move-track, .slider-move-btn {
    background: url(https://static.geetest.com/static/ant/sprite.1.2.4.png) no-repeat;
  }

  .refresh-btn, .close-btn {
    display: inline-block;
  }

  .slider-move .slider-move-track {
    line-height: 38px;
    font-size: 14px;
    text-align: center;
    white-space: nowrap;
    color: #88949d;
    -moz-user-select: none;
    -webkit-user-select: none;
    user-select: none;
  }

  .slider {
    user-select: none;
  }

  .slider-move .slider-move-btn {
    transform: translate(0px, 0px);
    background-position: -5px 11.79625%;
    position: absolute;
    top: -12px;
    left: 0;
    width: 66px;
    height: 66px;
  }

  .slider-move-btn:hover, .close-btn:hover, .refresh-btn:hover {
    cursor: pointer
  }

  .bottom .close-btn {
    width: 20px;
    height: 20px;
    background-position: 0 44.86874%;
  }

  .bottom .refresh-btn {
    width: 20px;
    height: 20px;
    background-position: 0 81.38425%;
  }

</style>


<style scoped>

</style>